package com.aplink.generic.widgets;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import sdt.brc.android.BarcodeReader;
import sdt.brc.android.BarcodeReaderResult;
import sdt.brc.android.BarcodeReaderUtil;
import sdt.brc.android.BarcodeScanDialog;
import sdt.brc.android.OnRecognitionListener;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.YuvImage;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.adapter.GalleryPagerAdapter;
import com.aplink.generic.controller.GenericApplication;
import com.aplink.generic.database.SqlMethods;
import com.aplink.generic.dictionary.GenericDictionary;
import com.aplink.generic.interfaces.OnActionBarSelectionListener;
import com.aplink.generic.interfaces.OnActivityResultListener;
import com.aplink.generic.interfaces.OnGetObjProInfo;
import com.aplink.generic.network.GenericFile;
import com.aplink.generic.pojo.ContentData;
import com.aplink.generic.pojo.GenericAttribute;
import com.aplink.generic.pojo.GenericObject;
import com.aplink.generic.pojo.controlspec.ControlSpec;
import com.aplink.generic.pojo.controlspec.GallerySpec;
import com.aplink.generic.util.BitmapUtis;
import com.aplink.generic.util.ResourcesHelper;
import com.aplink.generic.xmlparser.ContentDataParser;

public class ApLinkGallery extends ApLinkBaseView implements
        OnRecognitionListener {
    private static int LOAD_IMAGE = 2000;
    private static final int REQUEST_IMAGE_CAPTURE = 1000;
    /**
     * 
     */
    private static final long serialVersionUID = 1015143654244609071L;
    private GenericFile fileTemp;
    private final OnActionBarSelectionListener mActionBarSelectionListener = new OnActionBarSelectionListener() {

        @Override
        public boolean onSelectionItemSelected(final int itemPosition,
                final String value) {
            if (!TextUtils.isEmpty(ApLinkGallery.this.mGallerySpec
                    .getFilterBy())) {
                String where = null;
                if (value != null) {
                    final String selectWhere[] = ApLinkGallery.this.mGallerySpec
                            .getFilterBy().split(";");
                    final SqlMethods whereClause = SqlMethods.getInstance();

                    for (int i = 0; i < selectWhere.length; i++) {
                        final String solumnName = selectWhere[i];
                        whereClause.equal(solumnName, value);
                        if (i < (selectWhere.length - 1)) {
                            whereClause.and();
                        }
                    }
                    where = whereClause.toString();
                }
                final ArrayList<GenericObject> genericObjects = ApLinkGallery.this
                        .getDatabaseGet().getList(
                                ApLinkGallery.this.mContentData, where);
                ApLinkGallery.this.mGalleryPagerAdapter
                        .setGenericObjects(genericObjects);
                ApLinkGallery.this.mGalleryPagerAdapter.notifyDataSetChanged();
                return true;
            }
            return false;
        }
    };
    private final OnActivityResultListener mActivityResultListener = new OnActivityResultListener() {

        @Override
        public void onActivityResult(final int requestCode,
                final int resultCode, final Intent data) {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == ApLinkGallery.REQUEST_IMAGE_CAPTURE) {
                    final GenericObject genericObject = ApLinkGallery.this.mGalleryPagerAdapter
                            .add(ApLinkGallery.this.fileTemp.getLocalPath());
                    ApLinkGallery.this.mInsertObjects.add(genericObject);
                    ApLinkGallery.this.mInsertFiles
                            .add(ApLinkGallery.this.fileTemp);
                    ApLinkGallery.this.lastPage();
                } else if (requestCode == ApLinkGallery.LOAD_IMAGE) {
                    final Uri pickedImage = data.getData();
                    final String[] filePath = { MediaColumns.DATA };
                    Cursor cursor = ApLinkGallery.this.getActivity()
                            .getContentResolver()
                            .query(pickedImage, filePath, null, null, null);
                    cursor.moveToFirst();
                    final String imagePath = cursor.getString(cursor
                            .getColumnIndex(filePath[0]));
                    final Bitmap bitmap = BitmapUtis.getInstance()
                            .decodeSampledBitmapFromFile(
                                    imagePath,
                                    ApLinkGallery.this.mGallerySpec
                                            .getImageWidth(),
                                    ApLinkGallery.this.mGallerySpec
                                            .getImageHeight());
                    final GenericFile genericFile = BitmapUtis.getInstance()
                            .savebitmap(
                                    GenericApplication.getInstance()
                                            .getCreatedTime(), bitmap);

                    final GenericObject genericObject = ApLinkGallery.this.mGalleryPagerAdapter
                            .add(genericFile.getLocalPath());
                    ApLinkGallery.this.mInsertObjects.add(genericObject);
                    ApLinkGallery.this.mInsertFiles.add(genericFile);
                    ApLinkGallery.this.lastPage();
                    cursor.close();
                    cursor = null;
                }
            } else {
                if (ApLinkGallery.this.fileTemp != null) {
                    ApLinkGallery.this.fileTemp.delete();
                }
            }
        }
    };
    private BarcodeScanDialog mCamDlg = null;
    private final ContentData mContentData;
    private View mCtrlBarcodeResult = null;
    private final ArrayList<GenericFile> mDeleteFiles;
    private final ArrayList<GenericObject> mDeleteObjects;
    private GalleryPagerAdapter mGalleryPagerAdapter;
    private final GallerySpec mGallerySpec;
    private ArrayList<GenericObject> mGenericObjects;

    private final ArrayList<GenericFile> mInsertFiles;

    private final ArrayList<GenericObject> mInsertObjects;

    private final ViewPager mViewPager;

    private final OnClickListener onDeleteImage = new OnClickListener() {

        @Override
        public void onClick(final View v) {
            final int selectedIndex = ApLinkGallery.this.mViewPager
                    .getCurrentItem();
            final GenericObject deleteObject = ApLinkGallery.this.mGalleryPagerAdapter
                    .delete(selectedIndex);
            if (deleteObject != null) {
                ApLinkGallery.this.mDeleteFiles
                        .add(ApLinkGallery.this.mGalleryPagerAdapter
                                .getFile(deleteObject));
                ApLinkGallery.this.mDeleteObjects.add(deleteObject);
            }
        }
    };

    private final OnClickListener onScanBarcode = new OnClickListener() {

        @Override
        public void onClick(final View v) {
            if (!TextUtils.isEmpty(ApLinkGallery.this.mGallerySpec
                    .getScanBarcode())) {
                ApLinkGallery.this.mCamDlg = new BarcodeScanDialog(
                        ApLinkGallery.this.getActivity(),
                        "Purchased License key");
                if (ApLinkGallery.this.mCamDlg != null) {
                    ApLinkGallery.this.mCamDlg
                            .setBarcodeTypes(BarcodeReader.SDTBARCODE_ALL_1D);
                    ApLinkGallery.this.mCamDlg
                            .setRecognitionListener(ApLinkGallery.this);
                    ApLinkGallery.this.mCamDlg.show();
                }

                final String ctrlResultId = ApLinkGallery.this.mGallerySpec
                        .getBarcodeResultsID();
                if (!TextUtils.isEmpty(ctrlResultId)) {
                    ApLinkGallery.this.mCtrlBarcodeResult = ApLinkGallery.this
                            .getGenericFragment()
                            .getAPLinkViewByID(ctrlResultId).getView();
                }
            }
        }
    };

    private final OnClickListener onSelectFromGallery = new OnClickListener() {

        @Override
        public void onClick(final View v) {
            final Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            ApLinkGallery.this.getGenericFragment().startActivityForResult(
                    intent, ApLinkGallery.LOAD_IMAGE);
        }
    };

    private final OnClickListener onTakePicture = new OnClickListener() {

        @Override
        public void onClick(final View v) {
            final Intent takePictureIntent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(ApLinkGallery.this
                    .getActivity().getPackageManager()) != null) {
                ApLinkGallery.this.fileTemp = BitmapUtis.getInstance()
                        .createTempFile(
                                GenericApplication.getInstance()
                                        .getCreatedTime());
                final File photoFile = ApLinkGallery.this.fileTemp
                        .getRealFile();
                if (photoFile != null) {
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(photoFile));
                    ApLinkGallery.this.getGenericFragment()
                            .startActivityForResult(takePictureIntent,
                                    ApLinkGallery.REQUEST_IMAGE_CAPTURE);
                }
            }
        }
    };

    public ApLinkGallery(final GenericFragment genericFragment,
            final ControlSpec controlSpec, final View view) {
        super(genericFragment, controlSpec, view);
        this.mViewPager = (ViewPager) view;
        this.mGallerySpec = (GallerySpec) controlSpec;
        this.mInsertObjects = new ArrayList<GenericObject>();
        this.mDeleteObjects = new ArrayList<GenericObject>();
        this.mGenericObjects = new ArrayList<GenericObject>();
        this.mDeleteFiles = new ArrayList<GenericFile>();
        this.mInsertFiles = new ArrayList<GenericFile>();
        this.mContentData = ContentDataParser.getInstance().parseIntoObjProp(
                ResourcesHelper.getRawIdByName(this.mGallerySpec
                        .getContentData()));

    }

    @Override
    public void clear() {
        this.mDeleteFiles.clear();
        this.mDeleteObjects.clear();
        this.mInsertFiles.clear();
        this.mInsertObjects.clear();
    }

    public void closeScanBarcode() {
        if (this.mCamDlg != null) {
            this.mCamDlg.dismiss();
        }
    }

    public void firstPage() {
        this.mViewPager.setCurrentItem(0, true);
    }

    @Override
    public GenericAttribute getAttribute() {
        return null;
    }

    public ContentData getContentData() {
        return this.mContentData;
    }

    public ArrayList<GenericFile> getDeleteFiles() {
        return this.mDeleteFiles;
    }

    public ArrayList<GenericObject> getDeleteObjects() {
        return this.mDeleteObjects;
    }

    public ArrayList<GenericFile> getInsertFiles() {
        return this.mInsertFiles;
    }

    public ArrayList<GenericObject> getInsertObjects() {
        return this.mInsertObjects;
    }

    @Override
    public GenericDictionary<String, GenericAttribute> getListAttributes() {
        return null;
    }

    private String getSelectWhereValue(final String key) {
        final String subKey = key.split(Pattern.quote("."))[1];
        final String maintable = getGenericFragment().getContentData()
                .getMainTable();
        return getHashPassedValues().get(maintable + "." + subKey);
    }

    @Override
    public View getView() {
        return null;
    }

    public void hideCameraDialog() {
        if (this.mCamDlg != null) {
            this.mCamDlg.dismiss();
        }
    }

    @Override
    protected void initViewProperties() {
    }

    public void lastPage() {
        final int maxPage = this.mGalleryPagerAdapter.getCount();
        this.mViewPager.setCurrentItem(maxPage - 1, true);
    }

    @Override
    protected void loadBindingObject() {
        this.mGenericObjects = loadDatas();
        this.mGalleryPagerAdapter = new GalleryPagerAdapter(
                getChildFragmentManager(), this.mGenericObjects, this.mGallerySpec,
                getGenericFragment().getImageFetcher());
        this.mViewPager.setAdapter(this.mGalleryPagerAdapter);
        this.mViewPager.setOffscreenPageLimit(2);
    }

    private ArrayList<GenericObject> loadDatas() {
        ArrayList<GenericObject> genericObjects = new ArrayList<GenericObject>();
        if (!TextUtils.isEmpty(this.mGallerySpec.getFilterBy())) {
            final String selectWhere[] = this.mGallerySpec.getFilterBy().split(
                    ";");
            final SqlMethods whereClause = SqlMethods.getInstance();
            for (int i = 0; i < selectWhere.length; i++) {
                final String solumnName = selectWhere[i];
                whereClause.equal(solumnName, getSelectWhereValue(solumnName));
                if (i < (selectWhere.length - 1)) {
                    whereClause.and();
                }
            }
            genericObjects = getDatabaseGet().getList(this.mContentData,
                    whereClause.toString());
        }
        return genericObjects;
    }

    @Override
    protected void loadDefaultObject() {
        if (this.mGallerySpec.isLoadAll()) {
            this.mGenericObjects = getDatabaseGet().getList(this.mContentData,
                    null);
            this.mGalleryPagerAdapter = new GalleryPagerAdapter(
                    getChildFragmentManager(), this.mGenericObjects,
                    this.mGallerySpec, getGenericFragment().getImageFetcher());
            this.mViewPager.setAdapter(this.mGalleryPagerAdapter);
            this.mViewPager.setOffscreenPageLimit(2);
        } else {
            this.mGalleryPagerAdapter = new GalleryPagerAdapter(
                    getChildFragmentManager(), new ArrayList<GenericObject>(),
                    this.mGallerySpec, getGenericFragment().getImageFetcher());
            this.mViewPager.setAdapter(this.mGalleryPagerAdapter);
            this.mViewPager.setOffscreenPageLimit(2);
        }
    }

    public void nextPage() {
        final int nextPage = this.mViewPager.getCurrentItem() + 1;
        final int maxPage = this.mGalleryPagerAdapter.getCount();
        if (nextPage < maxPage) {
            this.mViewPager.setCurrentItem(nextPage, true);
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void onRecognitionResults(final List results, final YuvImage srcImage) {
        if (mCtrlBarcodeResult != null) {
            for (final BarcodeReaderResult barcodeReaderResult : (List<BarcodeReaderResult>) results) {
                final String barcodeValue = barcodeReaderResult.getValue();
                if (this.mCtrlBarcodeResult instanceof TextView) {
                    ((TextView) this.mCtrlBarcodeResult).setText(barcodeValue);
                } else if (this.mCtrlBarcodeResult instanceof EditText) {
                    ((EditText) this.mCtrlBarcodeResult).setText(barcodeValue);
                }
            }
        }
        this.mCamDlg.hide();
        final Bitmap bitmap = BarcodeReaderUtil.decodeImageToBitmap(srcImage);
        final GenericFile genericFile = BitmapUtis.getInstance().savebitmap(
                GenericApplication.getInstance().getCreatedTime(), bitmap);
        final GenericObject genericObject = this.mGalleryPagerAdapter
                .add(genericFile.getLocalPath());
        this.mInsertObjects.add(genericObject);
        this.mInsertFiles.add(genericFile);
        lastPage();

    }

    public void previousPage() {
        final int previousPage = this.mViewPager.getCurrentItem() - 1;
        if (previousPage >= 0) {
            this.mViewPager.setCurrentItem(previousPage, true);
        }
    }

    @Override
    protected void setEventListener() {
        getGenericFragment().setActivityResultListener(
                this.mActivityResultListener);
        if (this.mGallerySpec.getTakePictureID() != null) {
            final ApLinkBaseView apLinkBaseView = getGenericFragment()
                    .getAPLinkViewByID(this.mGallerySpec.getTakePictureID());
            if (apLinkBaseView != null) {
                apLinkBaseView.setOnClickListener(this.onTakePicture);
            } else if ((getGenericFragment().getFormDesign().get(
                    this.mGallerySpec.getTakePictureID()) != null)) {
                getGenericFragment().getFormDesign()
                        .get(this.mGallerySpec.getTakePictureID())
                        .setOnClickListener(this.onTakePicture);
            } else {
                getGenericFragment().findViewByID(
                        this.mGallerySpec.getTakePictureID())
                        .setOnClickListener(onTakePicture);
            }
        }

        if (this.mGallerySpec.getDeletePictureID() != null) {
            final ApLinkBaseView apLinkBaseView = getGenericFragment()
                    .getAPLinkViewByID(this.mGallerySpec.getDeletePictureID());
            if (apLinkBaseView != null) {
                apLinkBaseView.setOnClickListener(this.onDeleteImage);
            } else if ((getGenericFragment().getFormDesign().get(
                    this.mGallerySpec.getDeletePictureID()) != null)) {
                getGenericFragment().getFormDesign()
                        .get(this.mGallerySpec.getDeletePictureID())
                        .setOnClickListener(this.onDeleteImage);
            } else {
                getGenericFragment().findViewByID(
                        this.mGallerySpec.getDeletePictureID())
                        .setOnClickListener(onDeleteImage);
            }
        }

        if (this.mGallerySpec.getSelectFromGalleryID() != null) {
            final ApLinkBaseView apLinkBaseView = getGenericFragment()
                    .getAPLinkViewByID(
                            this.mGallerySpec.getSelectFromGalleryID());
            if (apLinkBaseView != null) {
                apLinkBaseView.setOnClickListener(this.onSelectFromGallery);
            } else if ((getGenericFragment().getFormDesign().get(
                    this.mGallerySpec.getSelectFromGalleryID()) != null)) {
                getGenericFragment().getFormDesign()
                        .get(this.mGallerySpec.getSelectFromGalleryID())
                        .setOnClickListener(this.onSelectFromGallery);
            } else {
                getGenericFragment().findViewByID(
                        this.mGallerySpec.getSelectFromGalleryID())
                        .setOnClickListener(onSelectFromGallery);
            }
        }

        if (this.mGallerySpec.getScanBarcode() != null) {
            final ApLinkBaseView apLinkBaseView = getGenericFragment()
                    .getAPLinkViewByID(this.mGallerySpec.getScanBarcode());
            if (apLinkBaseView != null) {
                apLinkBaseView.setOnClickListener(this.onScanBarcode);
            } else if ((getGenericFragment().getFormDesign().get(
                    this.mGallerySpec.getScanBarcode()) != null)) {
                getGenericFragment().getFormDesign()
                        .get(this.mGallerySpec.getScanBarcode())
                        .setOnClickListener(this.onScanBarcode);
            } else {
                getGenericFragment().findViewByID(
                        this.mGallerySpec.getScanBarcode()).setOnClickListener(
                        onScanBarcode);
            }
        }

        if (getGenericFragment().hasActionBarSelectionFor(
                this.mGallerySpec.getIDName())) {
            getGenericFragment().setActionBarSelectionListener(
                    this.mActionBarSelectionListener);
        }
    }

    @Override
    public void setObjPropInfoTemp(final OnGetObjProInfo getObjProInfo) {

    }

    @Override
    public void setOnClickListener(final OnClickListener onClickListener) {

    }

}
